package itheima.Lock01;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyThread extends Thread{
    //加上static关键字，表示这个类的所有对象共享ticket变量
    static int ticket = 0;

    //创建一个Object对象作为锁对象，一定要唯一
//    static Object obj = new Object();

    static Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            //这种处理方式叫做同步代码块
//            synchronized (/*obj*/Thread.class){
            lock.lock();
            try{
                if (ticket == 100){
                    break;
                }else {
                    Thread.sleep(10);
                    ticket++;
                    System.out.println(getName() + "正在卖第" + ticket + "张票！！！");
                    }
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
            }
//                if (ticket < 100){
//                    try {
//                            Thread.sleep(10);
//                    } catch (InterruptedException e) {
//                            throw new RuntimeException(e);
//                    }
//                    ticket++;
//                    System.out.println(getName() + "正在卖第" + ticket + "张票！！！");
//                }else {
//                    break;
//                }
//            }
    }
}

